﻿using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class PlayerController : MonoBehaviour,IDamageable
{
    private Rigidbody2D rb;
    private Animator anim;

    [Header("Player Setting")]
    public float speed;
    public float jumpForce;
    public float health;
    public float blinkRate;
    public float blinkTimes;
    public float invincibleTime;
    public float getHitTime = 0;

    [Header("Ground Check")]
    public Transform groundCheck;
    public float radius;
    public LayerMask groundLayer;

    [Header("Player State")]
    public bool isJump;
    public bool canJump;
    public bool isGround;
    public bool isWalk;
    public bool beAttack=false;

    public List<Transform> EnemyList = new List<Transform>();

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
    }

    void Update()
    {
        if (Input.GetButtonDown("Jump") && isGround)
        {
            canJump = true;
        }
        PlayerAnim();
        Attack();
        Debug.Log(isGround);
    }

    private void FixedUpdate()
    {
        GroundCheck();
        //当播放player_punch动画时不能执行跳跃移动等
        if (!anim.GetCurrentAnimatorStateInfo(0).IsName("player_punch")/* && !anim.GetCurrentAnimatorStateInfo(0).IsName("player_flying_kick")*/)
        {
            
            if (!beAttack)
            {
                Movement();
            }
            Jump();
            PlayerStateCheck();
        }
    }

    private void Movement()
    {
        float inputMove = Input.GetAxisRaw("Horizontal");
        rb.velocity = new Vector2(inputMove * speed, rb.velocity.y);

        if (inputMove != 0)
        {
            transform.localScale = new Vector3(inputMove, 1, 1);
        }
    }

    //检测玩家状态
    public void PlayerStateCheck()
    {
        if (Mathf.Abs(rb.velocity.x) > 0.1)
        {
            isWalk = true;
        }
        else
        {
            isWalk = false;
        }
    }

    private void PlayerAnim()
    {
        //if (rb.velocity.y == 0)
        //{
        //    anim.SetFloat("walk", Mathf.Abs(rb.velocity.x));
        //}
        anim.SetFloat("walk", Mathf.Abs(rb.velocity.x));
        anim.SetFloat("fall", rb.velocity.y);
        anim.SetBool("jump", isJump);
        anim.SetBool("ground", isGround);
    }

    private void GroundCheck()
    {
        isGround = Physics2D.OverlapCircle(groundCheck.position, radius, groundLayer);
        if (isGround)
        {
            rb.gravityScale = 1;
            isJump = false;
        }
    }

    private void Jump()
    {
        if (canJump)
        {
            isJump = true;
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
            rb.gravityScale = 3;
            canJump = false;
        }
        
    }

    private void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(groundCheck.position, radius);
    }

    public void Attack()
    {
        if (!anim.GetCurrentAnimatorStateInfo(0).IsName("player_punch") && isGround && !isWalk)
        {
            if (Input.GetKeyDown(KeyCode.J))
            {
                anim.SetTrigger("punch");
            }
        }

        if (isJump && !isGround && !anim.GetCurrentAnimatorStateInfo(0).IsName("player_flying_kick"))
        {
            if (Input.GetKeyDown(KeyCode.K))
            {
                anim.SetBool("flyingKick", true);
            }
        }
        else
        {
            if (isGround)
            {
                anim.SetBool("flyingKick", false);
            }
        }
    }

    public void GetHit(float damage)
    {
        if (health < 1)
        {
            health = 0;
        }
        else
        {
            if (Time.time > getHitTime)
            {
                health -= damage;
                HurtBlink(blinkRate,blinkTimes);//闪烁
                if (EnemyList[0].transform.position.x > transform.position.x)//判断敌人位置在玩家哪一侧
                {
                    rb.velocity = new Vector2(-4, 4);
                }
                else
                {
                    rb.velocity = new Vector2(4, 4);
                }
                //无敌时间
                getHitTime = Time.time + invincibleTime;
                StartCoroutine(HitOver());
            }
        }
    }

    IEnumerator HitOver()
    {
        if(health < 1)
        {
            Death();
            yield break;//生命值为0时直接结束协程
        }
        yield return new WaitForSeconds(0.5f);
        if (health > 0)
        {
            if (beAttack == true)
            {
                beAttack = false;
            }
        }
    }

    //受伤时闪烁效果
    public void HurtBlink(float blinkNum, float blinkTime)
    {
        StartCoroutine(DoBlink(blinkNum, blinkTime));
    }

    IEnumerator DoBlink(float blinkNum,float blinkTime)
    {
        for (int i = 0; i < blinkNum * 2; i++)
        {
            transform.GetComponent<SpriteRenderer>().enabled = !transform.GetComponent<SpriteRenderer>().enabled;
            yield return new WaitForSeconds(blinkTime);
        }
    }

    //检测玩家周围的敌人对象，并添加到列表中
    private void OnTriggerStay2D(Collider2D collision)
    {
        if (collision.CompareTag("Enemy") && !EnemyList.Contains(collision.transform))
        {
            EnemyList.Add(collision.transform);
        }
    }

    //当敌人离开检测范围，移除。
    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.CompareTag("Enemy"))
        {
            EnemyList.Remove(collision.transform);
        }
    }

    public void Death()
    {
        Destroy(gameObject);
    }
}
